﻿using Approval.Domain;
using AutoMapper;
using MediatR;
using PublicCommon;
using T_Person.APi.Applation.CommandHandlers.PersonnelHandlers;
using T_Person.BaseRep.Interface;
using T_Person.Domain;

namespace T_Person.APi.Applation.Commands.PersonnelCommand
{
    public class PersonnelUpdateCommand : IRequestHandler<PersonnelUpdateHandlers, int>
    {
        private readonly Cross_services_Helper _cross_services_helper;
        private readonly IEmployeeRep _employeeRep;
        private readonly IPersonnelRep personnelRep;
        private readonly IMapper mapper;

        public PersonnelUpdateCommand(IPersonnelRep personnelRep, IMapper mapper, Cross_services_Helper cross_services_helper, IEmployeeRep employeeRep)
        {
            this.personnelRep = personnelRep;
            this.mapper = mapper;
            _cross_services_helper = cross_services_helper;
            _employeeRep = employeeRep;
        }

        public async Task<int> Handle(PersonnelUpdateHandlers request, CancellationToken cancellationToken)
        {
            int results=0;
            request.UpdateDate = DateTime.Now;
            request.UpdateBy = "小红";
            var list = mapper.Map<Personnel>(request);
            var lists = await personnelRep.GetAloneByresult(x => x.EmployeeId == request.EmployeeId && !x.IsDel);
            if (list.AuditState>0)
            {
                var obj = new RLZRelation();
                obj.RLZId = list.Id.ToString();
                obj.ApprovalId = 1;
                obj.ApprovalName = "小明";
                var message = await _cross_services_helper.Post("http://10.31.60.9:8000/Approval/api/RLZRelation/RLZRelationAdd", obj);
                results = message.LastIndexOf("状态码");
            }
            if (results>0)
            {
                return await Task.FromResult(-1);
            }
            else
            {
                var employlist = await _employeeRep.GetAloneByresult(x => x.Ename == list.EmployeeId);
                employlist.EmployeeStyle++;
                await _employeeRep.Update(employlist);
            }
            if (lists.Id!=list.Id&&lists.AuditState!=3)
            {
                return await Task.FromResult(-2);
            }
            return await personnelRep.Update(list);
        }
    }
}
